package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.common.bcrypt.PasswordConfig;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.util.BeanHelper;
import com.usian.common.util.JwtUtils;
import com.usian.model.user.dtos.AppLoginDto;
import com.usian.model.user.dtos.UserInfoDto;
import com.usian.user.entity.ApUser;
import com.usian.user.service.IApUserLoginService;
import com.usian.user.service.IApUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Fay
 * @date 2022/7/15&11:17
 */
@Service
public class ApUserLoginServiceImpl implements IApUserLoginService {
    /**
     * APP登录
     * @param appLoginDto
     * @return
     */
    @Autowired
    private IApUserService apUserService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Map<String, Object> login(AppLoginDto appLoginDto) {
        //对参数进行校验
        if (appLoginDto==null){
            new LeadException(AppHttpCodeEnum.PARAM_REQUIRE,"缺少参数");
        }
        HashMap<String,Object> map = new HashMap();
        Integer userId=0;
        String phone = appLoginDto.getPhone();
        String password = appLoginDto.getPassword();
        if (!StringUtils.isEmpty(phone) && !StringUtils.isEmpty(password)){
            LambdaQueryWrapper<ApUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ApUser::getPhone,phone);
            ApUser apUser = apUserService.getOne(lambdaQueryWrapper);
            if (apUser==null){
                throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"该用户不存在");
            }
            boolean b = passwordEncoder.matches(appLoginDto.getPassword(), apUser.getPassword());
            if (!b){
                throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            UserInfoDto userInfoDto = BeanHelper.copyProperties(apUser, UserInfoDto.class);
            userId=apUser.getId();
            map.put("user",userInfoDto);
        }else {
            //如果传过来的机器码为空
            if (StringUtils.isEmpty(appLoginDto.getEquipmentId())){
                throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE,"机器码不存在");
            }
        }
        map.put("token", JwtUtils.generateTokenExpireInMinutes(userId,60*24*7));
        return map;
    }
}
